package com.thinktank.controller;

import java.io.*;
import java.sql.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import com.thinktank.dao.*;
import com.thinktank.vo.*;

import static com.thinktank.util.DbUtil.*;

public class NoticeController implements Controller {

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		// 세션 확인 및 쿠키 로그인
		HttpSession session = request.getSession();
		if (session.getAttribute("member") == null) {
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				String no = null;
				for (int i = 0; i < cookies.length; i++)
					if (cookies[i].getName().equals("no"))
						no = cookies[i].getValue();
				if (no != null) {
					System.out.println("쿠키로그인");
					Connection con = getConnection();
					MemberDao dao = new MemberDao(con);
					Member member = dao.cookieLogin(no);
					close(con);
					if (member != null)
						session.setAttribute("member", member);
				}
			}
		}
		// 방문 페이지 세션에 저장
		String url = null;
		if (request.getParameter("url") != null)
			url = request.getParameter("url");
		if (url != null)
			session.setAttribute("url", url);
		else {
			Member member = (Member) session.getAttribute("member");
			url = member.getmPage();
		}

		// 정보가 있으면 받고 없으면 초기화
		int page = 1;
		String pg = request.getParameter("pg");
		String field = request.getParameter("field");
		String query = request.getParameter("query");
		if (pg != null)
			page = Integer.parseInt(pg);
		if (field == null)
			field = "TITLE";
		if (query == null)
			query = "";
		else
			query = new String(query.getBytes("ISO-8859-1"), "utf-8");

		// 연결 후 DB 작업
		Connection con = getConnection();
		NoticeDao dao = new NoticeDao(con);
		List<Notice> list = dao.getAllNotices(page, field, query, url);
		int count = dao.elementsCount(field, query);
		close(con);

		// 세팅 후 넘기기
		request.setAttribute("list", list);
		request.setAttribute("query", query);
		request.setAttribute("count", count);

		return "notice.jsp";
	}

}
